package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"

	"nggs/util"
)

type config struct {
	JsonDir       string
	EnumFilePath  string
	TypeFilePath  string
	TemplateDir   string
	SourceCodeDir string
	Package       string
	Debug         bool
	BlackList     []string
	WhiteList     []string
	Extend        string
	Format        bool
	ReplaceNames  map[string]string
}

func loadConfig(cfgFilePath string) (cfg *config, err error) {
	err = util.IsDirOrFileExist(cfgFilePath)
	if err != nil {
		return
	}

	data, err := ioutil.ReadFile(cfgFilePath)
	if err != nil {
		return
	}

	cfg = &config{}

	err = json.Unmarshal(data, cfg)
	if err != nil {
		return
	}

	err = cfg.checkAndFormat()

	return
}

func (c *config) checkAndFormat() (err error) {
	_, err = os.Lstat(c.JsonDir)
	if err != nil {
		return fmt.Errorf("JsonDir有误，%s", err)
	}
	c.JsonDir, err = filepath.Abs(c.JsonDir)
	if err != nil {
		return fmt.Errorf("JsonDir有误，%s", err)
	}

	if c.EnumFilePath != "" {
		_, err = os.Lstat(c.EnumFilePath)
		if err != nil {
			return fmt.Errorf("EnumFilePath有误，%s", err)
		}
		c.EnumFilePath, err = filepath.Abs(c.EnumFilePath)
		if err != nil {
			return fmt.Errorf("EnumFilePath有误，%s", err)
		}
	}

	if c.TypeFilePath != "" {
		_, err = os.Lstat(c.TypeFilePath)
		if err != nil {
			return fmt.Errorf("TypeFilePath有误，%s", err)
		}
		c.TypeFilePath, err = filepath.Abs(c.TypeFilePath)
		if err != nil {
			return fmt.Errorf("TypeFilePath有误，%s", err)
		}
	}

	_, err = os.Lstat(c.TemplateDir)
	if err != nil {
		return fmt.Errorf("TemplateDir有误，%s", err)
	}
	c.TemplateDir, err = filepath.Abs(c.TemplateDir)
	if err != nil {
		return fmt.Errorf("TemplateDir有误，%s", err)
	}

	if c.SourceCodeDir == "" {
		return fmt.Errorf("SourceCodeDir不能为空")
	} else {
		//_, err = os.Lstat(c.SourceCodeDir)
		//if err != nil {
		//	return fmt.Errorf("SourceCodeDir有误，%s", err)
		//}
		c.SourceCodeDir, err = filepath.Abs(c.SourceCodeDir)
		if err != nil {
			return fmt.Errorf("SourceCodeDir有误，%s", err)
		}
	}

	if c.Package == "" {
		return fmt.Errorf("Package不能为空")
	}

	if c.Extend == "" {
		return fmt.Errorf("Extend不能为空")
	}

	return
}
